<?php
session_start();
require_once('mp3.php');

	$image_types=array('LARGEIMAGE','MEDIUMIMAGE','SMALLIMAGE');
	$album=$_GET['alb'];
	$artist=$_GET['art'];
	$SearchIndex='Music';
	$Keywords=urlencode($artist.' '.$album);
	$Keywords=urlencode($artist);
	$Operation = "ItemSearch";
	$Version = "2007-07-16";
	$ResponseGroup = "ItemAttributes,Images";
	$request=
	"http://ecs.amazonaws.com/onca/xml"
	. "?Service=AWSECommerceService"
	. "&AssociateTag=" . ''
	. "&AWSAccessKeyId=" . 'AKIAJ2AEQHCP7LK7WWEA'
	. "&Operation=" . $Operation
	. "&Version=" . $Version
	. "&SearchIndex=" . $SearchIndex
	. "&Keywords=" . $Keywords
	. "&ResponseGroup=" . $ResponseGroup;

	// Preparem la url i fem el get
	$request= preparaUrl($request,'6EgEu1ezIK0+sPnnSl3t/QE+Qt+7yGLP9afzAbtL');
	$response = file_get_contents($request);	
	// parsejem el resultat a una structura
	xml_parse_into_struct(xml_parser_create(),$response,$value_array,$index_array);
	// Obtenim un array amb MULTISIMA INFORMACIO XD
	// A recorrer l'struc value array per obtenir les imatges que volem
	if(isset($index_array['SMALLIMAGE'])||isset($index_array['MEDIUMIMAGE'])||isset($index_array['LARGEIMAGE']))
	{			
		$image_url = "";					
		for( $count = 0; $count < count($image_types); $count++) {
			// Si tenim imatges	
		   if (!isset($index_array[$image_types[$count]])) continue;										
			$index = $index_array[$image_types[$count]][0]+1;
			if($value_array[$index]['tag']=='URL')	{
				$image_url=$value_array[$index]['value'];
				break;
			}
			else continue;
		}
		// Ja tenim les imatges;											
		$index=strrpos($image_url,'/');
		$image_name=substr($image_url,$index+1);
		$image_name=mysql_escape_string(urldecode($image_name));
		$file_str=file_get_contents($image_url);
        $myruta = "./caratules/".$image_name;
		$file_handle = fopen($myruta, 'w');
		fwrite($file_handle, $file_str);
		fclose($file_handle);	
		// fer un set de la BD
        $mp3 = new Mp3($_GET['id']);
        $mp3->set_caratula($myruta);
        $mp3->update();
        ?><meta http-equiv="Refresh" content="0;url=./editplaylist.php"><?php



	}

	




// Funcio trobada per ahi que et deixa llesta la url per conectarte a amazon... Cool!
function preparaUrl($url,$amazon_secret_key) {
	    $CONFIG['AMAZON_SECRET_KEY']=$amazon_secret_key;
	    $original_url = $url;
	    // Decode anything already encoded
	    $url = urldecode($url);
	    // Parse the URL into $urlparts
	    $urlparts= parse_url($url);
	    // Build $params with each name/value pair
	    foreach (split('&', $urlparts['query']) as $part) {
	        if (strpos($part, '=')) {
	            list($name, $value) = split('=', $part, 2);
	         } else {
	            $name = $part;
	            $value = '';
	        }
	        $params[$name] = $value;
	    }
	    // Include a timestamp if none was provided
	    if (empty($params['Timestamp'])) {
	        $params['Timestamp'] = gmdate('Y-m-d\TH:i:s\Z');
	    }
	    // Sort the array by key
	    ksort($params);
	    // Build the canonical query string
	    $canonical       = '';
	    foreach ($params as $key => $val) {
	        $canonical  .= "$key=".rawurlencode($val)."&";
	    }
	    // Remove the trailing ampersand
	    $canonical = preg_replace("/&$/", '', $canonical);
	    // Some common replacements and ones that Amazon specifically mentions
	    $canonical  = str_replace(array(' ', '+', ',', ';'), array('%20', '%20', urlencode(','), urlencode(':')), $canonical);
	    // Build the si
	    $string_to_sign             = "GET\n{$urlparts['host']}\n{$urlparts['path']}\n$canonical";
	    // Calculate our actual signature and base64 encode it
	    $signature            = base64_encode(hash_hmac('sha256', $string_to_sign, $CONFIG['AMAZON_SECRET_KEY'], true));
	    // Finally re-build the URL with the proper string and include the Signature
	    $url = "{$urlparts['scheme']}://{$urlparts['host']}{$urlparts['path']}?$canonical&Signature=".rawurlencode($signature);
	    return $url;
}


?>
